package player

import (
	"context"
	"github.com/topfreegames/pitaya"
	"github.com/topfreegames/pitaya/component"
	"github.com/topfreegames/pitaya/fairy/constants"
	"github.com/topfreegames/pitaya/fairy/manager"
	protos2 "github.com/topfreegames/pitaya/fairy/protos"
	"github.com/topfreegames/pitaya/logger"
)

type PlayerDealer struct {
	component.Base
}

func NewPlayerDealer() *PlayerDealer {
	return &PlayerDealer{}
}

/**
获取一个全局唯一的sessionId
*/
func (p *PlayerDealer) OnSessionCreated(ctx context.Context,req *protos2.GatePOnSessionCreated) (*protos2.GatePOnSessionCreatedRet,error) {
	sessionId := manager.OnlinePlayerManager.GenerateSessionId()
	return &protos2.GatePOnSessionCreatedRet{
		SessionId: &sessionId,
	},nil
}

/**
处理客户端连接关闭
*/
func (p *PlayerDealer) OnSessionClosed(ctx context.Context,req *protos2.GatePOnSessionClosed) (*protos2.GatePOnSessionClosedRet,error) {
	//查找等待登录游戏服务器所在的登录服务器 给登录服务器发送玩家连接消息 登录服务器做相应处理
	if req.SessionIds != nil && len(req.SessionIds) > 0 {
		svId := ""
		for _,sessionId := range req.SessionIds {
			if len(svId) == 0 {
				svId = manager.OnlinePlayerManager.GetPlayerOnLoginServerId(sessionId)
			}

			manager.OnlinePlayerManager.RemovePlayerOnLoginServer(sessionId)
		}

		if len(svId) > 0 {
			//玩家在登录服务器上 给玩家推送消息
			reply := &protos2.GatePOnSessionClosedRet{}
			err := pitaya.RPCTo(ctx,svId,constants.PHOnSessionClosed,reply,req)
			if err != nil {
				logger.Log.Errorf("[GateDealer] onSessionClosed failed,error=%s",err.Error())
			}
		}

	}

	//todo:玩家在游戏服上的处理逻辑
	return &protos2.GatePOnSessionClosedRet{},nil
}

/**
玩家关联了loginServer
 */
func (p *PlayerDealer) PlayerOnLoginServer(ctx context.Context,req *protos2.LPSessionOnLoginServer) (*protos2.PLSessionOnLoginServerRet,error) {
	manager.OnlinePlayerManager.SetPlayerOnLoginServerId(*req.SessionId,*req.ServerId)
	return &protos2.PLSessionOnLoginServerRet{},nil
}

